//
//  NetworkAdapter.m
//  Basic
//
//  Created by 裴烨烽 on 16/5/21.
//  Copyright © 2016年 BasicPod. All rights reserved.
//

// 网络适配器
#import "NetworkAdapter.h"
#import "NetworkEngine.h"


@implementation NetworkAdapter

+(instancetype)sharedAdapter{
    static NetworkAdapter *_sharedAdapter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedAdapter = [[NetworkAdapter alloc] init];
    });
    return _sharedAdapter;
}

#pragma mark - 短链接
-(void)fetchWithPath:(NSString *)path requestParams:(NSDictionary *)requestParams responseObjectClass:(Class)responseObjectClass succeededBlock:(void(^)(BOOL isSucceeded,id responseObject, NSError *error))block{
    __weak typeof(self)weakSelf = self;

    NetworkEngine *networkEngine;
    if (JAVA_Port.length){
        networkEngine = [[NetworkEngine alloc]initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@:%@",JAVA_Host,JAVA_Port]]];
    } else {
        networkEngine = [[NetworkEngine alloc]initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@",JAVA_Host]]];
    }
    
    [networkEngine fetchWithPath:path requestParams:requestParams responseObjectClass:responseObjectClass succeededBlock:^(BOOL isSucceeded, id responseObject, NSError *error) {
        if (!weakSelf){
            return ;
        }
        
        if (isSucceeded){
            if ([responseObject isKindOfClass:[NSDictionary class]]){           // 字典类别
                // 判断是否请求成功
                NSNumber *errorNumber = [responseObject objectForKey:@"errCode"];
                if (errorNumber.integerValue == 200){           // 请求成功
                    if (responseObjectClass == nil){
                        NSDictionary *dic = [responseObject objectForKey:@"data"];
                        block(YES,dic,nil);
                        return;
                    }
                    NSDictionary *respnseDic = (NSDictionary *)responseObject;
                    NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithDictionary:respnseDic];
                    if ([respnseDic.allKeys containsObject:@"obj"]){
                        [infoDic setObject:[respnseDic objectForKey:@"obj"] forKey:@"data"];
                    } else if ([respnseDic.allKeys containsObject:@"data1"] && [respnseDic.allKeys containsObject:@"data2"]){
                        NSMutableDictionary *tempDataDic = [NSMutableDictionary dictionary];
                        [tempDataDic setObject:[respnseDic objectForKey:@"data1"] forKey:@"data1"];
                        [tempDataDic setObject:[respnseDic objectForKey:@"data2"] forKey:@"data2"];
                        
                        [infoDic setObject:tempDataDic forKey:@"data"];
                    }
                    
                    if ([[infoDic objectForKey:@"data"] isKindOfClass:[NSArray class]]){
                        NSDictionary *infoTempListDic = @{@"infoList":[infoDic objectForKey:@"data"]};
                        [infoDic setObject:infoTempListDic forKey:@"data"];
                    }
                    
                    FetchModel *responseModelObject = (FetchModel *)[[responseObjectClass alloc] initWithJSONDict:[infoDic objectForKey:@"data"]];
                    block(YES,responseModelObject,nil);
                    
                } else if (errorNumber.integerValue == 401){            // 重新登录
                   
//                    if ([NetworkAdapter sharedAdapter].delegate && [[NetworkAdapter sharedAdapter].delegate respondsToSelector:@selector(pandaNotLoginNeedLoginManager)]){
//                        [[NetworkAdapter sharedAdapter].delegate pandaNotLoginNeedLoginManager];
//                    }
                } else {                                        // 业务错误
                    [StatusBarManager statusBarHidenWithText:@"服务器好像出了点问题"];
                    id errInfo = [responseObject objectForKey:@"errMsg"];
                    if ([errInfo isKindOfClass:[NSString class]]){
                        NSString *errorInfo = [responseObject objectForKey:@"errMsg"];
                        if (!errorInfo.length){
                            errorInfo = @"系统错误，请联系管理员";
                        }
                        NSDictionary *dict = @{NSLocalizedDescriptionKey: errorInfo};
                        NSError *bizError = [NSError errorWithDomain:PDBizErrorDomain code:errorNumber.integerValue userInfo:dict];
                        
                        block(NO,responseObject,bizError);
                        return;
                    } else {
                        return;
                    }
                }
            }
        }
    }];
}



- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    
    SBJSON *jsonSDK = [[SBJSON alloc] init];
    NSString *jsonStr = [jsonSDK stringWithObject:dic error:&parseError];
    return jsonStr;
}


+ (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;

    SBJSON *jsonSDK = [[SBJSON alloc] init];
    NSString *jsonStr = [jsonSDK stringWithObject:dic error:&parseError];
    return jsonStr;
}


@end

